package com.badibadi.slide;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.badibadi.activity.BaseActivity;
import com.badibadi.infos.photoModel__;
import com.badibadi.mytools.Constants;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

//import android.view.ViewTreeObserver;
//import android.graphics.Bitmap;
//import android.graphics.Canvas;
//import android.graphics.drawable.BitmapDrawable;
//import android.renderscript.Allocation;
//import android.renderscript.RenderScript;
//import android.renderscript.ScriptIntrinsicBlur;
//import android.view.LayoutInflater;
//import android.view.MotionEvent;

public class MainActivity extends BaseActivity implements View.OnClickListener {

	private ProgressWheel pwTwo;
	int wheelProgress = 0;

	private static final int SUCCESS = 1;
	private static final int ERROR = 2;
	private ViewPager viewPager;
	private LayoutInflater mInflater;
	private List<View> mPageViews = new ArrayList<View>();

	private ImageView playBtn;
	private boolean playStat = true;
	private boolean playTag = true;
	private int num = 0;
	private MediaPlayer mPlayer;
	private ImageView out;

	private TextView textView1;
	private photoModel__ slide_use;
	private String act_name;

	// private DisplayImageOptions options;

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.main);
		try {
			act_name = getIntent().getStringExtra("act_name");
		} catch (Exception e) {
			// TODO: handle exception
		}
		initView();
	}

	private void initView() {
		// options = new DisplayImageOptions.Builder()
		// .showStubImage(R.drawable.ic_stub)
		// .showImageForEmptyUri(R.drawable.noimage)
		// .showImageOnFail(R.drawable.noimage).cacheInMemory()
		// .cacheOnDisc().displayer(new RoundedBitmapDisplayer(0)).build();
		slide_use = (photoModel__) getIntent().getSerializableExtra(
				"slide_imgs");
		out = (ImageView) findViewById(R.id.out);
		out.setOnClickListener(this);

		pwTwo = (ProgressWheel) findViewById(R.id.progress_bar_two);

		playBtn = (ImageView) findViewById(R.id.play_btn);
		playBtn.setOnClickListener(this);

		viewPager = (ViewPager) findViewById(R.id.viewpager);
		mInflater = LayoutInflater.from(this);

		textView1 = (TextView) findViewById(R.id.textView1);
		// textView1.setVisibility(View.INVISIBLE);
		try {
			textView1.setText(act_name);
		} catch (Exception e) {
			// TODO: handle exception
			textView1.setText("出错，名字为空");
		}

		mPageViews = new ArrayList<View>();

		// 初始化图片资源
		for (int i = 0; i < slide_use.getImgPath().size(); i++) {
			final ImageView imageView = new ImageView(this);
			// imageView.setImageResource(imgs[i]);
			imageView.setScaleType(ScaleType.FIT_CENTER);
			// ImageLoader.getInstance().displayImage(
			// Constants.BadiDownImgUrl
			// + slide_use.getImgPath().get(0).getPath()
			// + Constants.appWaterfall, imageView);
			/*ImageLoader
					.getInstance()
					.loadImage(
							Constants.BadiDownImgUrl
									+ slide_use.getImgPath().get(i).getPath()
									+ Constants.appPhoto4img_1,*/
									ImageLoader
									.getInstance()
									.loadImage(
											Constants.BadiDownImgUrl
													+ slide_use.getImgPath().get(i).getPath()
													+ Constants.appWaterfall,
							new ImageLoadingListener() {

								@Override
								public void onLoadingStarted(String arg0,
										View arg1) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onLoadingFailed(String arg0,
										View arg1, FailReason arg2) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onLoadingComplete(String arg0,
										View arg1, Bitmap arg2) {
									// TODO Auto-generated method stub
									imageView.setImageBitmap(arg2);
								}

								@Override
								public void onLoadingCancelled(String arg0,
										View arg1) {
									// TODO Auto-generated method stub

								}
							});

			// imageView.setScaleType(ScaleType.CENTER_CROP);
			mPageViews.add(imageView);
		}

		viewPager.setAdapter(new ViewPagerAdapters(mPageViews, this));
		viewPager.setCurrentItem(0);
		viewPager.setOffscreenPageLimit(1);
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					// ((MainActivity)
					// getActivity()).getSlideMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
					break;
				default:
					// ((MainActivity)
					// getActivity()).getSlideMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
					break;
				}

			}

			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		/**
		 * viewPager.setOnTouchListener(new View.OnTouchListener() {
		 * 
		 * @Override public boolean onTouch(View view, MotionEvent motionEvent)
		 *           { return true; } });
		 **/
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.play_btn:
			if (playStat) {
				playBtn.setBackgroundResource(R.drawable.btn_stop);

				if (num == 0) {
					if (slide_use.getMusicPath() != null) {
						playMusic();
					}
				} else {
					if (null != mPlayer) {
						mPlayer.start();
					}
				}
				playStat = false;
				playTag = true;
				playImg();
				playTime();

				// applyBlur();

			}

			else {
				playBtn.setBackgroundResource(R.drawable.btn_play);
				playStat = true;
				playTag = false;

				if (null != mPlayer) {
					mPlayer.pause();
				}
			}

			break;

		case R.id.out:
			finish();
			playTag = false;
			if (null != mPlayer) {
				mPlayer.stop();
				mPlayer = null;
			}
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == 4) {
			finish();
			playTag = false;
			if (null != mPlayer) {
				mPlayer.stop();
				mPlayer = null;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void playMusic() {
//		   ("异常信息为======");
		mPlayer = new MediaPlayer();
		try {
			mPlayer.reset();
			// mPlayer.setDataSource("http://www.uniclubber.com/Public/music/back_in_time.mp3");
			// mPlayer.setDataSource(Constants.YuyingDownLoad
			// + slide_use.getMusicPath());//内网使用
			mPlayer.setDataSource(Constants.BadiWebImgUrl
					+ slide_use.getMusicPath());// 外网使用
			mPlayer.prepare();
			mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer player) {
				}
			});
			mPlayer.start();
		} catch (Exception e) {
//			   ("异常信息为" + e.toString());
		}
	}

	private void playImg() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (playTag && num < 29) {
					Message msg = new Message();
					try {
						Thread.sleep(2000);
						msg.what = SUCCESS;
					} catch (InterruptedException e) {
						msg.what = ERROR;
						   
					}
					mcHandler.sendMessage(msg);
				}
			}
		}).start();
	}

	private void playTime() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (playTag && wheelProgress < 60) {
					pwTwo.incrementProgress();
					wheelProgress++;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						   
					}
				}
			}
		}).start();
	}

	/**
	 * private void applyBlur() {
	 * viewPager.getViewTreeObserver().addOnPreDrawListener(new
	 * ViewTreeObserver.OnPreDrawListener() {
	 * 
	 * @Override public boolean onPreDraw() {
	 *           viewPager.getViewTreeObserver().removeOnPreDrawListener(this);
	 *           viewPager.buildDrawingCache();
	 * 
	 *           Bitmap bmp = viewPager.getDrawingCache(); blur(bmp, textView1);
	 *           return true; } }); }
	 * 
	 *           // 首先根据view的大小，从bkg生成一个剪裁后的图像； //
	 *           然后根据radius，将剪裁后的图像模糊处理；最后将模糊处理的图像设置到view上。
	 * @SuppressLint("NewApi") private void blur(Bitmap bkg, View view) { long
	 *                         startMs = System.currentTimeMillis(); float
	 *                         scaleFactor = 8; float radius = 2;
	 * 
	 * 
	 *                         Bitmap overlay = Bitmap.createBitmap((int)
	 *                         (view.getMeasuredWidth()/scaleFactor), (int)
	 *                         (view.getMeasuredHeight()/scaleFactor),
	 *                         Bitmap.Config.ARGB_8888); Canvas canvas = new
	 *                         Canvas(overlay);
	 *                         canvas.translate(-view.getLeft()/scaleFactor,
	 *                         -view.getTop()/scaleFactor); canvas.scale(1 /
	 *                         scaleFactor, 1 / scaleFactor); Paint paint = new
	 *                         Paint();
	 *                         paint.setFlags(Paint.FILTER_BITMAP_FLAG);
	 *                         canvas.drawBitmap(bkg, 0, 0, paint);
	 * 
	 *                         overlay = FastBlur.doBlur(overlay, (int)radius,
	 *                         true); view.setBackground(new
	 *                         BitmapDrawable(getResources(), overlay));
	 * 
	 *                         }
	 **/

	public Handler mcHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				num++;
//				   ("当前页数为" + num
//						% slide_use.getImgPath().size());
				viewPager.setCurrentItem(num);
				if (num == 30) {
					if (null != mPlayer) {
						pwTwo.setVisibility(View.INVISIBLE);
						out.setVisibility(View.VISIBLE);
						playBtn.setVisibility(View.INVISIBLE);
						textView1.setVisibility(View.VISIBLE);

						try {
							Thread.sleep(4000);

						} catch (InterruptedException e) {
							   
						}
						mPlayer.stop();
						// finish();
					}

				}

				break;

			case ERROR:
				break;
			}
		}
	};
}
